package com.tech.thread.juc.locks.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description:
 * @Author: zl
 * @Date: 2019/7/26 14:25
 */
public class BoundedBuffer {
    final Lock lock = new ReentrantLock();
    final Condition notFull = lock.newCondition();
    final Condition notEmpty = lock.newCondition();
    // 定义缓存区的大小为100
    final Object[] items = new Object[100];
    int putptr, takeptr, count;

    public void put(Object x) throws InterruptedException {
        lock.lock();
        try {
            while (count == items.length)
                notFull.await();
            items[putptr] = x;
            if (++putptr == items.length) putptr = 0;
            ++count;
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    public Object take() throws InterruptedException {
        lock.lock();
        try {
            // 缓冲区空了，消费者线程进入等待。（等待被唤醒）
            while (count == 0)
                notEmpty.await();
            // 从0下标位置开始取出元素，当取到最后一个元素时，下标归为0
            Object x = items[takeptr];
            if (++takeptr == items.length) takeptr = 0;// 因为元素的下标是从0开始的所以先++操作
            --count;
            // 唤醒生产则线程，生产数据到缓存区
            notFull.signal();
            return x;
        } finally {
            lock.unlock();
        }
    }
}
